//
//  Alamofire+Extension.swift
//
//  Created by yuhus on 2023/8/11.
//

import Alamofire

extension DataRequest {
  @discardableResult
  public func validate<S: Sequence>(responseCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
    validate { [unowned self] _, _, data in
      self.validate(statusCode: acceptableStatusCodes, data: data)
    }
  }
  
  fileprivate func validate<S: Sequence>(statusCode acceptableStatusCodes: S, data: Data?) -> ValidationResult
  where S.Iterator.Element == Int {
    guard let data,
          let res = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
          let statusCode = res["code"] as? Int else {
      return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
    }
    
    if acceptableStatusCodes.contains(statusCode) {
      return .success(())
    } else {
      let reason = AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: statusCode)
      return .failure(AFError.responseValidationFailed(reason: reason))
    }
  }
}

extension AFError {
  public func getValidationCode() -> Int? {
    guard case let .responseValidationFailed(reason) = self,
          case let .unacceptableStatusCode(code) = reason else {
      return nil
    }
    return code
  }
}
